import { useMarketingApi } from '/@/api/marketing';
import { ElMessage } from 'element-plus';

const { editPosition, addPosition, getPositionList } = useMarketingApi();

export const rules = {
	positionName: [{ required: true, message: '请输入位置名称', trigger: ['blur'] }],
};
export const positionOptions = [
	{ name: '页面位置', value: '页面位置' },
	{ name: '首页顶部广告位', value: '首页顶部广告位' },
	{ name: '首页文案宣传位', value: '首页文案宣传位' },
	{ name: '首页轮播图', value: '首页轮播图' },
	{ name: '首页优惠券', value: '首页优惠券' },
	{ name: 'fall is here', value: 'fall is here' },
	{ name: 'you might like', value: 'you might like' },
	{ name: '首页分类入口', value: '首页分类入口' },
];
export const useInit = () => {
	const loading = ref(false);
	const page = ref({
		pageSize: 99,
		current: 1,
	});
	const searchForm = ref({});
	const tableData = ref([]);
	const init = async () => {
		loading.value = true;
		let res = await getPositionList({ ...page.value, ...searchForm.value });
		loading.value = false;
		if (res.code !== 200) return;
		tableData.value = res.data.data.map((item) => {
			item.picsArr = JSON.parse(item.pics || '[]');
			if (item.picsArr) item.picsSrcArr = item.picsArr.map(({ src }) => src);
			return item;
		});
	};
	onMounted(init);
	return {
		page,
		positionOptions,
		searchForm,
		loading,
		tableData,
		init,
	};
};
export const useEdit = (init) => {
	const formRef = ref();
	const isAdd = ref(false);
	const addDialogVisible = ref(false);
	const ruleForm = ref({});
	const saveLoading = ref(false);
	const submit = () => {
		formRef.value.validate(async (valid) => {
			if (valid) {
				ruleForm.value.pics = JSON.stringify(ruleForm.value.picsArr);
				const request = isAdd.value ? addPosition : editPosition;
				saveLoading.value = true;
				let res = await request(ruleForm.value);
				saveLoading.value = false;
				if (res.code !== 200) return;
				ElMessage.success('保存成功！');
				addDialogVisible.value = false;
				init();
			}
		});
	};
	return {
		isAdd,
		rules,
		ruleForm,
		addDialogVisible,
		formRef,
		saveLoading,
		title: computed(() => (isAdd ? '新增位置' : '编辑位置')),
		changeStatus() {},
		toEdit(row) {
			if (formRef.value) formRef.value.clearValidate();
			ruleForm.value = JSON.parse(JSON.stringify(row));
			if (!ruleForm.value.score) ruleForm.value.score = 0;
			isAdd.value = false;
			addDialogVisible.value = true;
			console.log('9------', ruleForm.value);
		},
		toAdd() {
			if (formRef.value) formRef.value.clearValidate();
			ruleForm.value = {
				score: 0,
			};
			isAdd.value = true;
			addDialogVisible.value = true;
		},
		submit,
	};
};
